import os
from PyPDF2 import PdfMerger


def merge_pdfs_in_folder(folder_path, target_pdf):
    merger = PdfMerger()

    # Get a list of all PDF files in the specified folder
    pdf_files = [f for f in os.listdir(folder_path) if f.endswith('.PDF')]

    # Sort the PDF files by name
    pdf_files.sort()

    # Merge all PDF files into the target PDF
    for pdf_file in pdf_files:
        with open(os.path.join(folder_path, pdf_file), 'rb') as file:
            merger.append(file)

    # Save the merged PDF to the target path
    with open(target_pdf, 'wb') as output:
        merger.write(output)


# Example usage
folder_path = r'C:\Users\masaikk\Downloads\announcements\announcements'
target_pdf = r'C:\Users\masaikk\Downloads/target.pdf'
merge_pdfs_in_folder(folder_path, target_pdf)